package com.glodon.paas.account.security.oauth2.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.MapAccessor;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.PropertyPlaceholderHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import com.glodon.paas.account.service.UserService;

/**
 * @author Don Li
 */
@Controller
@SessionAttributes("authorizationRequest")
public class UserApprovalService {
	
	@Autowired
	private UserService userService; 
	
    @RequestMapping("/oauth2/confirm_access")
    public ModelAndView getAccessConfirmation(Map<String, Object> model) throws Exception {
    	getScope(model);
        return new ModelAndView("authorize_oauth2", model);
    }

    @RequestMapping("/oauth2/error")
    public ModelAndView handleError(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("error", request.getAttribute("error"));
        return new ModelAndView("accessDenied", model);
    }

    
    private void getScope(Map<String, Object> model){
    	Map<String,String> map = ((AuthorizationRequest)model.get("authorizationRequest")).getAuthorizationParameters();  	
    	
    	model.put("scopeInfo",userService.getScopeInfo(map.get("scope")));
    }
    /**
     * Simple String template renderer.
     */
    private static class SpelView implements View {

        private final String template;

        private final SpelExpressionParser parser = new SpelExpressionParser();

        private final StandardEvaluationContext context = new StandardEvaluationContext();

        private PropertyPlaceholderHelper helper;

        private PropertyPlaceholderHelper.PlaceholderResolver resolver;

        public SpelView(String template) {
            this.template = template;
            this.context.addPropertyAccessor(new MapAccessor());
            this.helper = new PropertyPlaceholderHelper("${", "}");
            this.resolver = new PropertyPlaceholderHelper.PlaceholderResolver() {
                public String resolvePlaceholder(String name) {
                    Expression expression = parser.parseExpression(name);
                    Object value = expression.getValue(context);
                    return value == null ? null : value.toString();
                }
            };
        }

        public String getContentType() {
            return "text/html";
        }

        public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            Map<String, Object> map = new HashMap<String, Object>(model);
            map.put("path", (Object) request.getContextPath());
            context.setRootObject(map);
            String result = helper.replacePlaceholders(template, resolver);
            response.getWriter().append(result);
        }

    }

    private static String APPROVAL = "<html><body><h1>OAuth Approval</h1>"
            + "<p>Do you authorize '${authorizationRequest.clientId}' to access your protected resources?</p>"
            + "<form id='confirmationForm' name='confirmationForm' action='${path}/oauth2/authorize' method='post'><input name='user_oauth_approval' value='true' type='hidden'/><label><input name='authorize' value='Authorize' type='submit'></label></form>"
            + "<form id='denialForm' name='denialForm' action='${path}/oauth2/authorize' method='post'><input name='user_oauth_approval' value='false' type='hidden'/><label><input name='deny' value='Deny' type='submit'></label></form>"
            + "</body></html>";

    private static String ERROR = "<html><body><h1>OAuth Error</h1><p>${error.summary}</p></body></html>";
}
